import { defineStore } from "pinia";

// useStore could be anything like useUser, useCart
// the first argument is a unique id of the store across your application
const useStore = defineStore({
  // other options...
  id: "common",
  state: () => ({
    clientWidth: 0,
    clientHeight: 0,
    darkMode: true,
    appVersion: "1.0.0",
    showSidebar: true,
    sidebarWidth: 200,
    // address: "",
    // host: "",
    hostName: "",
    isReal: false,
    mousePosition: { x: 0, y: 0 },
    lastMouseMove: 0,
  }),
  getters: {
    availableWidth() {
      return this.clientWidth - (this.showSidebar ? this.sidebarWidth : 0);
    },
    getClientWidth() {
      return this.clientWidth;
    },
    getClientHeight() {
      return this.clientHeight;
    },
    getClientSize() {
      return {
        width: this.clientWidth,
        height: this.clientHeight,
      };
    },
    isMouseFree() {
      return new Date().getTime() - this.lastMouseMove > 10 * 1000;
    },
    isWideEnough() {
      return this.clientWidth >= 1440;
    },
  },
  actions: {
    setClientSize(payload) {
      this.clientWidth = payload.width;
      this.clientHeight = payload.height;
    },
    setDarkMode(payload) {
      this.darkMode = payload;
    },
    register() {
      this.handleResize();
      this.getIP();
      window.addEventListener("resize", this.handleResize);
      window.addEventListener("mousemove", this.handleMouseMove);
    },
    handleResize() {
      if (
        typeof window.innerWidth !== "undefined" &&
        window.innerWidth &&
        typeof window.innerHeight !== "undefined" &&
        window.innerHeight
      ) {
        this.setClientSize({
          width: window.innerWidth,
          height: window.innerHeight,
        });
        // console.log("clientSize:", this.getClientSize);
      }
    },
    handleMouseMove(e) {
      this.mousePosition = {
        x: e.clientX,
        y: e.clientY,
      };
      this.lastMouseMove = new Date().getTime();
    },
    getIP() {
      // this.address =
      //   window.location.protocol + "//" + window.location.host + "/";
      // this.host = window.location.host;
      this.hostName = window.location.hostname;
      this.isReal =
        this.hostName.includes("127.0.0.") ||
        this.hostName.includes("172.22.215.") ||
        this.hostName.includes("10.202.91.");
      console.log(
        "hostName: ",
        this.hostName,
        this.isReal ? " (RealMode)" : " (FakeMode)"
      );
    },
  },
});

export default useStore;
